import { Button } from "@/components/ui/btn/button1";
import { useState, useEffect } from "react";
import { Routes, Route, useNavigate } from "react-router-dom";
import { navItems } from "./nav-items";
import { DefaultSelector } from "@/components/ui/selector/default_selector";
import { note_types } from "@/api/view/Index_api";

const Index = () => {
  const navigate = useNavigate();
  const [options] = useState<string[]>(note_types);
  const [selectedType, setSelectedType] = useState(() => {
    // 从localStorage获取上次保存的笔记类型，如果没有则返回空字符串
    return localStorage.getItem("userNoteType") || "";
  });
  // 当selectedType值改变时，保存到localStorage
  useEffect(() => {
    localStorage.setItem("userNoteType", selectedType);
  }, [selectedType]);

  const [hasError, setHasError] = useState(false); // 错误状态
  return (
    <div className="flex h-full flex-col bg-gray-50 p-6">
      <div className="mb-6 flex items-center justify-between">
        <div className="flex space-x-4">
          <Button variant="default" onClick={() => navigate(navItems[0].href)}>
            热点分析
          </Button>
          <Button variant="default" onClick={() => navigate(navItems[1].href)}>
            笔记模板提取
          </Button>
          <Button variant="default" onClick={() => navigate(navItems[2].href)}>
            笔记生成
          </Button>
        </div>
        <div className="flex items-center space-x-4">
          <DefaultSelector
            value={selectedType}
            onValueChange={(value) => {
              setSelectedType(value);
            }}
            options={options}
            placeholder="选择笔记类型"
            className="w-48"
            errorFlag={hasError}
            setErrorFlag={setHasError}
          />
        </div>
      </div>
      <div className="flex h-full min-h-0 flex-col">
        <Routes>
          {navItems.map((item) => (
            <Route
              key={item.href}
              path={item.href}
              element={item.page({
                selectedType: selectedType,
                setIndexUiError: setHasError,
              })}
            />
          ))}
        </Routes>
      </div>
    </div>
  );
};
export default Index;
